package com.xtkj.superclub_shop.config;

import com.xtkj.commons.SnowflakeIdWorker;
import com.xtkj.superclub_entity.entity.shop.ProItem;
import com.xtkj.superclub_shop.dao.ICartDao;
import lombok.extern.slf4j.Slf4j;
import org.quartz.JobExecutionContext;
import org.quartz.JobExecutionException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.HashOperations;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.scheduling.quartz.QuartzJobBean;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.Iterator;
import java.util.Map;
import java.util.Set;


/**
 * @author lizheqi
 * @create 2020-01-08-14:03
 */
@Slf4j
public class Schedule extends QuartzJobBean {

    @Autowired
    private RedisTemplate redisTemplate;
    @Autowired
    private StringRedisTemplate stringRedisTemplate;
    @Autowired
    private ICartDao cartDao;
    @Autowired
    private SnowflakeIdWorker snowflakeIdWorker;

    private static final String prefix = "*";

    private SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");

    @Scheduled(cron = "0 0/30 * * * *")//每天凌晨执行
    @Override
    protected void executeInternal(JobExecutionContext jobExecutionContext) throws JobExecutionException {
        log.info("LikeTask-------- {}", sdf.format(new Date()));
        //将 Redis 里的阅读信息同步到数据库里
        HashOperations ops = redisTemplate.opsForHash();
        Set<String> keys = stringRedisTemplate.keys(prefix);
        //获取所有的键即用户编号
        Iterator<String> iterator = keys.iterator();//获取迭代器
        while (iterator.hasNext()){
            //拿到用户编号
            String userId = iterator.next();
            //拿到用户的购物车
            Map entries = ops.entries(userId);
            //获取购物车迭代器
            Iterator iterator1 = entries.keySet().iterator();
            while (iterator1.hasNext()){
                String key = iterator1.next().toString();
                String[] strs = key.split("-");
                //获取产品编号
                String proId = strs[0];
                //获取颜色编号
                String colorId = strs[1];
                //获取尺寸编号
                String sizeId = strs[2];
                //获取该列项对应的数量
                int cnt = Integer.valueOf(entries.get(key).toString());
                String proItemId = snowflakeIdWorker.nextId()+"";
                //雪花生成商品列项编号
                ProItem proItem = new ProItem();
                proItem.setProItemId(proItemId);
                proItem.setUserId(userId).setProId(proId).setColorId(colorId).setSizeId(sizeId).setCnt(cnt);
                //将其存入到购物车表
                cartDao.insert(proItem);
            }
        }
    }

}

